import { useUpload } from '@/uni_modules/wot-design-uni'
import { commonAPI } from '@/api/index.js';

const { startUpload, abort, chooseFile, UPLOAD_STATUS } = useUpload()

// 生成基于当前时间的随机文件路径
const generateRandomFilePath = (file) => {
	const url = file.url;
	const lastDotIndex = url.lastIndexOf('.');
	const extension = lastDotIndex !== -1 ? url.substring(lastDotIndex + 1) : 'png';

	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');

	// 生成随机字符串
	const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
	let randomStr = '';
	for (let i = 0; i < 14; i++) {
		randomStr += chars.charAt(Math.floor(Math.random() * chars.length));
	}

	return `${year}/${month}/${randomStr}.${extension}`;
}

export const getFormData = ((file) => {
	return new Promise((resolve, reject) => {
		commonAPI.get('AlibabaCloud/credential').then(res => {
			if (res.code == 200) {
				const ossInfo = res.result;
				const imgUrl = generateRandomFilePath(file)

				const formData = {
					key: imgUrl,
					policy: ossInfo.policy,
					'x-oss-signature-version': ossInfo.x_oss_signature_version,
					'x-oss-credential': ossInfo.x_oss_credential,
					'x-oss-date': ossInfo.x_oss_date,
					'x-oss-signature': ossInfo.signature,
					'x-oss-security-token': ossInfo.security_token,
					success_action_status: '200'
				}

				resolve({ formData, host: ossInfo.host })
			}
		})
	})
})

export const uploadImage = (file) => {
	return new Promise(async (resolve, reject) => {
		const { formData, host } = await getFormData(file);


		startUpload(file, {
			action: host,
			formData,
			onSuccess(res) {
				resolve(formData.key)
			},
			onError(err) {
				console.log('上传失败', err)
			},
			onProgress(progress) {
				// console.log('上传进度', progress)
			}
		})

	})
}